package com.crowd.controller;

import com.crowd.constant.CrowdConstant;
import com.crowd.po.MemberPO;
import com.crowd.service.api.MysqlProviderService;
import com.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Stone
 * @date 2020/6/23 17:11
 */
@RestController
public class MysqlProviderController {
    @Autowired
    private MysqlProviderService service;

    /**
     * @Author:Stone
       * @Param loginAcct:
       * @return: com.crowd.util.ResultEntity<com.crowd.po.MemberPO>
     * @Date: 2020/6/30 15:58
     * @Description: 通过账号来找Member对象
    */
    @RequestMapping("/get/memberpo/by/login/acct/remote")
    public ResultEntity<MemberPO> getMemberPOByLoginAcctRemote(@RequestParam String loginAcct){

        try{
            MemberPO memberPO = service.getMemberPOByLoginAcct(loginAcct);
            return ResultEntity.successWithData(memberPO);
        }catch (Exception e){
            return ResultEntity.failed(e.getMessage());
        }
    }

    @RequestMapping("/save/member/remote")
    public ResultEntity<String> saveMember(@RequestBody MemberPO memberPO){
        try{
            service.saveMemberPO(memberPO);
        }catch (Exception e){
            // 在数据库已经设置了loginAcct为unique，
            // 如果字段重复，就会报DuplicateKeyException
            if(e instanceof DuplicateKeyException){
                return ResultEntity.failed(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }

            return ResultEntity.failed(e.getMessage());
        }
        return ResultEntity.successWithoutData();
    }
}
